package com.xiaohui.gwc.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaohui.gwc.mapper.Jwtuser_roleMapper;
import com.xiaohui.gwc.mapper.UserMapper;
import com.xiaohui.gwc.mode.*;
import com.xiaohui.gwc.service.RegiseterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @Author: Poppin
 * @Date: 2021/11/30 12:41
 * @Version: 1.0
 */
@Service
public class RegisterServiceImpl implements RegiseterService {

    private UserMapper userMapper;
    private Jwtuser_roleMapper jwtuser_roleMapper;




    @Autowired
    private RegisterServiceImpl(UserMapper userMapper,Jwtuser_roleMapper jwtuser_roleMapper) {
        this.userMapper = userMapper;
        this.jwtuser_roleMapper = jwtuser_roleMapper;
    }

    @Override
    public Result jc(String username) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",username);
        int count = userMapper.selectCount(queryWrapper);
        if (count==0){
            return new Result<String>(
                    ReturnCode.SUCCESS.getCode(), ReturnCode.SUCCESS.getType(), "成功","可以注册"
            );
        }else {
            return new Result<String>(
                    ReturnCode.ERROR.getCode(), ReturnCode.ERROR.getType(), "失败","不允许注册"
            );
        }
    }

    @Override
    public Result register(String username, String password) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(10);

        Users users = new Users();
        users.setUsername(username);
        users.setPassword(bCryptPasswordEncoder.encode(password));
        users.setRealname("");
        users.setJian("");
        users.setToken("");
        users.setLocked(false);
        users.setEnabled(true);
        int count = userMapper.insert(users);
        if (count == 1){
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("username",username);
            users = userMapper.selectOne(queryWrapper);
            Jwtuser_role jwtuser_role = new Jwtuser_role();
            jwtuser_role.setRid(2);
            jwtuser_role.setUid(users.getUserid());
            int count1 = jwtuser_roleMapper.insert(jwtuser_role);
            if (count1 == 1){
                return new Result<AffectedRows>(
                        ReturnCode.SUCCESS.getCode(), ReturnCode.SUCCESS.getType(), "注册成功",new AffectedRows(count1)
                );
            }else {
                return new Result<AffectedRows>(
                        ReturnCode.ERROR.getCode(), ReturnCode.ERROR.getType(), "注册失败",new AffectedRows(count1)
                );
            }
        }else {
            return new Result<AffectedRows>(
                    ReturnCode.ERROR.getCode(), ReturnCode.ERROR.getType(), "注册失败",new AffectedRows(count)
            );
        }
    }
}

